package com.zrrd.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.zrrd.gmall.common.result.Result;
import com.zrrd.gmall.common.util.IpUtil;
import com.zrrd.gmall.model.user.UserInfo;
import com.zrrd.gmall.service.constant.RedisConst;
import com.zrrd.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        System.out.println("收到的参数====》"+userInfo);
        //调用业务层的登录
        UserInfo info = userService.login(userInfo);
        if (info!=null){
            //使用uuid生成一个token
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //创建Map集合 存入昵称 和 token （前端）
            Map<String, Object> map= new HashMap<>();
            map.put("nickName",info.getNickName());
            map.put("token",token);
            //用户信息存入Redis
            JSONObject userJson = new JSONObject();
            userJson.put("userId",info.getId().toString());
            userJson.put("ip", IpUtil.getIpAddress(request));
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,userJson.toJSONString(),
                   RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS );
            //返回
            return Result.ok(map);
        }else {
            return Result.fail().message("用户不存在或密码错误");
        }
    }

    //退出登录
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        //获取请求头中的token
        String token = request.getHeader("token");
        //将登录成功时 存在Redis中的用户信息删除掉
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
        return Result.ok();
    }
}
